package com.example.eurekacustomer.controller;

import com.example.eurekacustomer.service.HystrixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.logging.Logger;

/**
 * @Auther: zyb
 * @Date: 2018/11/2 17:06
 * @Description: Ribbon的访问方式
 */
@RestController
@RequestMapping("/ribbon")
public class RibbonController {

    private Logger logger = Logger.getLogger(RibbonController.class.toString());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HystrixService hystrixService;

    @GetMapping("/getCustomers")
    public String getCustomers() {
        String url = "http://eureka-client/index";
        String body = restTemplate.getForEntity(url, String.class).getBody();
        logger.info(body);
        return body;
    }

    @GetMapping("/getUserName")
    public String getUserName(@RequestParam String name) {
        String url = "http://eureka-client/getUserName?name={1}";
//        return restTemplate.getForEntity(url, String.class, name).getBody();
        return restTemplate.getForObject(url, String.class, name);
    }

    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam String name, @RequestParam String password) {
        String url = "http://eureka-client/getUserInfo?name={1}&password={2}";
//        return restTemplate.getForEntity(url, String.class, name, password).getBody();//String.class为执行返回值类型
        return restTemplate.getForObject(url, String.class, name, password);
    }

    @GetMapping("/getUserInfoByMap")
    public String getUserInfoByMap(@RequestParam String name, @RequestParam String password) {
        return hystrixService.getUserInfoByMap(name, password);
    }

    @PostMapping("/putUserName")
    public String putUserName(@RequestParam String name, @RequestParam String password) {
        String url = "http://eureka-client/putUserName";
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("name", name);
        map.add("password", password);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
        return restTemplate.postForEntity(url, httpEntity, String.class).getBody();
    }

}
